<template>
  <el-dialog
    v-model="dialogVisible"
    title="模板管理"
    width="800px"
    :close-on-click-modal="false"
    class="template-manager-dialog"
  >
    <div class="template-manager">
      <!-- 模板列表 -->
      <div class="template-list">
        <div class="list-header">
          <h3>模板列表</h3>
          <el-button type="primary" @click="handleAddTemplate">
            <el-icon><Plus /></el-icon>
            新建模板
          </el-button>
        </div>
        <el-scrollbar height="400px">
          <div
            v-for="template in templates"
            :key="template.id"
            class="template-item"
            :class="{ active: currentTemplate?.id === template.id }"
            @click="selectTemplate(template)"
          >
            <div class="template-info">
              <h4>{{ template.name }}</h4>
              <p class="description">{{ template.template.description }}</p>
            </div>
            <div class="template-actions">
              <el-button
                type="danger"
                circle
                @click.stop="handleDeleteTemplate(template)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </el-scrollbar>
      </div>

      <!-- 模板编辑表单 -->
      <div class="template-editor" v-show="currentTemplate || isCreating">
        <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="100px"
          class="template-form"
        >
          <el-form-item label="模板名称" prop="name">
            <el-input
              v-model="formData.name"
              placeholder="请输入模板名称"
            />
          </el-form-item>

          <el-form-item label="任务名称" prop="skillName">
            <el-input
              v-model="formData.skillName"
              placeholder="请输入任务名称"
            />
          </el-form-item>

          <el-form-item label="任务描述" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              :rows="3"
              placeholder="请输入任务描述"
            />
          </el-form-item>

          <el-form-item label="任务阶段">
            <div class="stages-container">
              <div
                v-for="(stage, index) in formData.stages"
                :key="index"
                class="stage-item"
              >
                <div class="stage-header">
                  <el-input
                    v-model="stage.name"
                    placeholder="阶段名称"
                    class="stage-name"
                  />
                  <el-button
                    type="danger"
                    circle
                    @click="removeStage(index)"
                    :disabled="formData.stages.length === 1"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>

                <div class="nodes-container">
                  <div
                    v-for="(node, nodeIndex) in stage.nodes"
                    :key="nodeIndex"
                    class="node-item"
                  >
                    <el-input
                      v-model="node.name"
                      placeholder="节点名称"
                      class="node-name"
                    />
                    <el-button
                      type="danger"
                      circle
                      @click="removeNode(stage, nodeIndex)"
                      :disabled="stage.nodes.length === 1"
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </div>
                  <el-button
                    type="primary"
                    plain
                    @click="addNode(stage)"
                    class="add-node-btn"
                  >
                    <el-icon><Plus /></el-icon>
                    添加节点
                  </el-button>
                </div>
              </div>

              <el-button
                type="primary"
                plain
                @click="addStage"
                class="add-stage-btn"
              >
                <el-icon><Plus /></el-icon>
                添加阶段
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          保存模板
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { Delete, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { createModel, updateModel, deleteModel, getModelList } from '@/api/model'

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  }
})

const emit = defineEmits(['update:modelValue'])

const dialogVisible = ref(props.modelValue)
const formRef = ref(null)
const saving = ref(false)
const currentTemplate = ref(null)
const isCreating = ref(false)
const templates = ref([])
const loading = ref(false)

const formData = reactive({
  id: null,
  name: '',
  skillName: '',
  description: '',
  stages: []
})

const rules = {
  name: [
    { required: true, message: '请输入模板名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  skillName: [
    { required: true, message: '请输入任务名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 500, message: '长度不能超过 500 个字符', trigger: 'blur' }
  ]
}

// 获取模板列表
const fetchTemplates = async () => {
  try {
    loading.value = true
    const response = await getModelList({
      current: 1,
      size: 100
    })
    // 处理返回的数据，将 modelData 解析为对象
    templates.value = response.data.data.records.map(item => ({
      id: item.id,
      name: item.modelName,
      template: JSON.parse(item.modelData)
    }))
  } catch (error) {
    console.error('获取模板列表失败:', error)
    ElMessage.error('获取模板列表失败')
  } finally {
    loading.value = false
  }
}

// 监听对话框显示状态
watch(() => props.modelValue, (val) => {
  dialogVisible.value = val
  if (val) {
    fetchTemplates()
  }
})

watch(() => dialogVisible.value, (val) => {
  emit('update:modelValue', val)
  if (!val) {
    resetForm()
  }
})

// 方法
const handleAddTemplate = () => {
  resetForm()
  isCreating.value = true
  formData.stages = [{
    name: '',
    nodes: [{ name: '' }]
  }]
}

const selectTemplate = (template) => {
  isCreating.value = false
  currentTemplate.value = template
  formData.id = template.id
  formData.name = template.name
  formData.skillName = template.template.skillName
  formData.description = template.template.description
  formData.stages = JSON.parse(JSON.stringify(template.template.stages))
}

const handleDeleteTemplate = async (template) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该模板吗？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteModel(template.id)
    ElMessage.success('删除成功')
    await fetchTemplates()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除模板失败:', error)
      ElMessage.error('删除模板失败')
    }
  }
}

const addStage = () => {
  formData.stages.push({
    name: '',
    nodes: [{ name: '' }]
  })
}

const removeStage = (index) => {
  formData.stages.splice(index, 1)
}

const addNode = (stage) => {
  stage.nodes.push({ name: '' })
}

const removeNode = (stage, index) => {
  stage.nodes.splice(index, 1)
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  formData.id = null
  formData.name = ''
  formData.skillName = ''
  formData.description = ''
  formData.stages = []
  currentTemplate.value = null
  isCreating.value = false
}

const handleCancel = () => {
  resetForm()
  dialogVisible.value = false
}

const handleSave = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    // 验证阶段和节点
    for (const stage of formData.stages) {
      if (!stage.name.trim()) {
        ElMessage.warning('请填写所有阶段名称')
        return
      }
      for (const node of stage.nodes) {
        if (!node.name.trim()) {
          ElMessage.warning('请填写所有节点名称')
          return
        }
      }
    }

    saving.value = true
    
    // 构建模板数据
    const templateData = {
      id: formData.id || 0,
      modelName: formData.name,
      modelData: JSON.stringify({
        skillName: formData.skillName,
        description: formData.description,
        stages: formData.stages
      }),
      createTime: '',
      updateTime: ''
    }
    
    if (templateData.id) {
      // 更新现有模板
      await updateModel(templateData)
    } else {
      // 创建新模板
      await createModel(templateData)
    }
    
    ElMessage.success('模板保存成功')
    await fetchTemplates()
    resetForm()
    dialogVisible.value = false
  } catch (error) {
    console.error('保存模板失败:', error)
    ElMessage.error('保存模板失败')
  } finally {
    saving.value = false
  }
}

// 组件挂载时获取模板列表
onMounted(() => {
  if (dialogVisible.value) {
    fetchTemplates()
  }
})
</script>

<style scoped>
.template-manager {
  display: flex;
  gap: 24px;
  height: 600px;
}

.template-list {
  width: 300px;
  border-right: 1px solid #e4e7ed;
  padding-right: 24px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.list-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.template-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 8px;
}

.template-item:hover {
  background-color: #f5f7fa;
}

.template-item.active {
  background-color: #ecf5ff;
}

.template-info {
  flex: 1;
  margin-right: 12px;
}

.template-info h4 {
  margin: 0 0 4px;
  font-size: 14px;
  color: #303133;
}

.template-info .description {
  margin: 0;
  font-size: 12px;
  color: #909399;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.template-editor {
  flex: 1;
  overflow-y: auto;
}

.template-form {
  padding-right: 20px;
}

.stages-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.stage-item {
  background: #f5f7fa;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #e4e7ed;
}

.stage-header {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px dashed #dcdfe6;
}

.stage-name {
  flex: 1;
}

.stage-name :deep(.el-input__wrapper) {
  background-color: #fff;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.stage-name :deep(.el-input__inner) {
  font-weight: 500;
  font-size: 15px;
}

.nodes-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding-left: 12px;
}

.node-item {
  display: flex;
  gap: 12px;
}

.node-name {
  flex: 1;
}

.node-name :deep(.el-input__wrapper) {
  background-color: #fafafa;
}

.node-name :deep(.el-input__inner) {
  font-size: 14px;
  color: #606266;
}

.add-node-btn {
  margin-left: 0;
  width: 100%;
}

.add-stage-btn {
  width: 100%;
  margin-top: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .template-manager {
    flex-direction: column;
    height: auto;
  }

  .template-list {
    width: 100%;
    border-right: none;
    border-bottom: 1px solid #e4e7ed;
    padding-right: 0;
    padding-bottom: 24px;
    margin-bottom: 24px;
  }

  .template-editor {
    width: 100%;
  }

  .template-form {
    padding-right: 0;
  }

  .stage-item {
    padding: 12px;
  }

  .nodes-container {
    padding-left: 8px;
  }

  .add-node-btn {
    margin-left: 0;
    width: 100%;
  }
}
</style> 